const mongoose = require('mongoose');
const DBUtils = require('./utils');
const log = require('../libs/log4js')('accountDB');
const accountSchema = mongoose.Schema({
  year: Number,
  month: Number,
  date: String,
  money: Number,
  desc: String,
  dateTime: Number,
  createDate: String,
  updateDate: String,
  user: String,
  payType: String, // 付款类型
  consumptionType: String,
  id: String // 消费类型
});
const AccountBook = mongoose.model('accountBook', accountSchema);
const db = new DBUtils({
  DB: AccountBook,
  logName: 'ACCOUNTDB'
});
const insert = db.insert.bind(db);
const query = db.queryAll.bind(db);
const search = db.queryByPageNo.bind(db);
const computedCount = db.computedCount.bind(db);
const insetArray = function (data) {
  return new Promise((s, r) => {
    AccountBook.insertMany(data, (err) => {
      if (err) {
        log.warn('数据保存失败');
        console.log(err);
        r(0);
      }
      log.info('数据存储成功');
      s(1);
    });
  });
};
const update = db.update.bind(db);
// const del = db.deleteOne.bind(db);
// const delM = db.deleteMany.bind(db);

const aggregate = function ({match, group}) {
  return new Promise((s, r) => {
    AccountBook.aggregate([{$match: match}, {$group: group}], function (err, data) {
      if (err) {
        log.warn('聚合计算失败');
        console.log(err);
        r(0);
      }
      log.info('聚合计算成功');
      s(data);
    });
  });
};
module.exports = {
  insert,
  query,
  insetArray,
  update,
  aggregate,
  search,
  computedCount
  // del,
  // delM
};
